//
//  SMSVC.m
//  MovieDate
//
//  Created by 杨运涛 on 16/3/31.
//  Copyright © 2016年 MovieDate. All rights reserved.
//

#import "SMSVC.h"
#import "RegisterVC.h"
#import "AppDelegate.h"

@interface SMSVC () <UITextFieldDelegate> {
    BOOL boolSendPhoneCode;
    NSMutableDictionary *dictNext;
}

@property (weak, nonatomic) IBOutlet UIButton *pBtnSendPhoneCode;
@property (weak, nonatomic) IBOutlet UIButton *pBtnNext;

@property (weak, nonatomic) IBOutlet UITextField *pTxtPhone;
@property (weak, nonatomic) IBOutlet UITextField *pTxtPhoneCode;

@end

@implementation SMSVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)initInfo {
    [super initInfo];
    
    if (self.pEm_Type == em_login) {
        [_pBtnNext setTitle:@"登录" forState:UIControlStateNormal];
    }
    
    dictNext = [NSMutableDictionary dictionary];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    
    NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor], NSForegroundColorAttributeName, [UIFont boldSystemFontOfSize:20], NSFontAttributeName, nil];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    self.title = @"短信验证";
    
    UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    [btnBack setImage:[UIImage imageNamed:@"back2"] forState:UIControlStateNormal];
    [btnBack setTitle:@"   " forState:UIControlStateNormal];
    [btnBack.titleLabel setFont:[UIFont boldSystemFontOfSize:18]];
    [btnBack setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnBack setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [btnBack addTarget:self action:@selector(selPopOrDismissViewController) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarItem = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem = leftBarItem;
}

- (IBAction)btnUserRegisterAction:(id)sender {
    [TDNetwork testDynCodePostURL:testCodeIP andPhoneNumber:self.pTxtPhone.text andCode:self.pTxtPhoneCode.text complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
        if (succeed) {
            
            switch ([ret intValue]) {
                case 1:
                    [dictNext setValue:[dictionary valueForKey:@"res"] forKey:@"phoneCode"];
                    [SVProgressHUD dismiss];
                    [self performSegueWithIdentifier:@"idfRegisterVC" sender:nil];
                    break;
                    
                case -1:
                    [SVProgressHUD showErrorWithStatus:@"账号已经注册"];
                    
                    break;
                case -2:
                    [SVProgressHUD showErrorWithStatus:@"验证码不正确"];
                    
                    break;
                    
                case -3:
                    [SVProgressHUD showErrorWithStatus:@"验证码超过3分钟"];
                    
                    
                    break;
                case -4:
                    [SVProgressHUD showErrorWithStatus:@"手机号或者验证码（为空）不正确"];
                    
                    
                    break;
                default:
                    [SVProgressHUD showErrorWithStatus:@""];
                    break;
            }
        }else{
            [SVProgressHUD showErrorWithStatus:@"网络请求失败"];
        }
    }];
}

- (IBAction)setPBtnSendPhoneCodeAction:(UIButton *)pBtnSendPhoneCode
{
    if ([self selMobileUseful:self.pTxtPhone.text].length != 11) {
        return;
    }
    [dictNext setValue:self.pTxtPhone.text forKey:@"phone"];
    
    [TDNetwork sendDynCodePostURL:sendDynCodeIP andPhoneNumber:self.pTxtPhone.text andType:@"1" complete:^(BOOL succeed, NSString *ret, NSDictionary *dictionary) {
        if ([ret isEqualToString:@"1"]) {
            boolSendPhoneCode = YES;
            
            pBtnSendPhoneCode.backgroundColor = [UIColor grayColor];
            __block int timeout = 59; //倒计时时间
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
            dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
            dispatch_source_set_event_handler(_timer, ^{
                if(timeout<=0){ //倒计时结束，关闭
                    dispatch_source_cancel(_timer);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        //设置界面的按钮显示 根据自己需求设置
                        [pBtnSendPhoneCode setTitle:@"获取验证码" forState:UIControlStateNormal];
                        pBtnSendPhoneCode.backgroundColor = [UIColor colorWithRed:255.0/255 green:198.0/255 blue:88.0/255 alpha:1];
                        pBtnSendPhoneCode.userInteractionEnabled = YES;
                    });
                }else{
                    int seconds = timeout % 60;
                    NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        //设置界面的按钮显示 根据自己需求设置
                        [UIView beginAnimations:nil context:nil];
                        [UIView setAnimationDuration:1];
                        pBtnSendPhoneCode.titleLabel.text = [NSString stringWithFormat:@"%@秒重新发送",strTime];
                        [pBtnSendPhoneCode setTitle:[NSString stringWithFormat:@"%@秒重新发送",strTime] forState:UIControlStateNormal];
                        [UIView commitAnimations];
                        
                        pBtnSendPhoneCode.userInteractionEnabled = NO;
                    });
                    timeout--;
                }
            });
            dispatch_resume(_timer);
        } else if ([ret isEqualToString:@"-1"]) {
            [SVProgressHUD showInfoWithStatus:@"手机号已注册"];
        } else {
            [SVProgressHUD showInfoWithStatus:@"发送失败"];
        }
    }];
}

//判断是否是手机号
- (NSString *)selMobileUseful:(NSString *)mobile
{
    if (mobile.length < 11)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入有效手机号码"];
        return @"";
    }else{
        NSString *CM_NUM = @"1[0-9]{10}$";
        
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        
        if (isMatch1) {
            return mobile;
        } else {
            [SVProgressHUD showErrorWithStatus:@"请输入有效手机号码"];
            return @"";
        }
    }
    return nil;
}
#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@""]) {
        if (textField.text.length <= 11) {
            [_pBtnSendPhoneCode setEnabled:NO];
            [_pBtnSendPhoneCode setBackgroundColor:[UIColor colorWithRed:180/255.0f green:179/255.0f blue:175/255.0f alpha:1]];
        }
        
        return YES;
    }
    
    if (textField.tag == 1201) {
        if (textField.text.length == 10) {
            [_pBtnSendPhoneCode setBackgroundColor:[UIColor colorWithRed:253/255.0f green:177/255.0f blue:53/255.0f alpha:1]];
            [_pBtnSendPhoneCode setEnabled:YES];
        } else if (textField.text.length == 11) {
            [_pBtnSendPhoneCode setBackgroundColor:[UIColor colorWithRed:253/255.0f green:177/255.0f blue:53/255.0f alpha:1]];
            [_pBtnSendPhoneCode setEnabled:YES];
            return NO;
        } else {
            [_pBtnSendPhoneCode setBackgroundColor:[UIColor colorWithRed:180/255.0f green:179/255.0f blue:175/255.0f alpha:1]];
            [_pBtnSendPhoneCode setEnabled:NO];
        }
    
    }
        
    if (textField.text.length > 0 && boolSendPhoneCode && _pTxtPhone.text.length > 0) {
        [_pBtnNext setBackgroundColor:[UIColor colorWithRed:253/255.0f green:177/255.0f blue:53/255.0f alpha:1]];
        [_pBtnNext setEnabled:YES];
    } else {
        [_pBtnNext setBackgroundColor:[UIColor colorWithRed:180/255.0f green:179/255.0f blue:175/255.0f alpha:1]];
        [_pBtnNext setEnabled:NO];
    }
    
    return YES;
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"idfRegisterVC"]) {
        RegisterVC *nextVC = segue.destinationViewController;
        nextVC.pDictInfo = dictNext;
    }
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}


@end
